package com.ccteam.fluidmusic.ui.moment.comment

import androidx.lifecycle.*
import com.ccteam.fluidmusic.utils.Event
import com.ccteam.fluidmusic.view.bean.ErrorMessage
import com.ccteam.fluidmusic.view.bean.LoadMessage
import com.ccteam.fluidmusic.view.bean.PublishCommentData
import com.ccteam.model.Resource
import com.ccteam.network.ApiError
import com.ccteam.shared.domain.moment.comment.PublishCommentDataUseCase
import com.orhanobut.logger.Logger
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/3/30
 *
 * 发布评论ViewModel
 */
@HiltViewModel
class PublishCommentViewModel @Inject constructor(
    private val publishCommentDataUseCase: PublishCommentDataUseCase,
    savedStateHandle: SavedStateHandle
): ViewModel() {

    private val _publishCommentInfo = MutableLiveData<PublishCommentData>(
           savedStateHandle["commentInfo"]
    )
    val publishCommentInfo: LiveData<PublishCommentData> get() = _publishCommentInfo

    private val _loadMessage = MutableLiveData<Event<LoadMessage>>()
    val loadMessage: LiveData<Event<LoadMessage>> get() = _loadMessage

    /**
     * 发布评论
     */
    fun publishComment(comment: String){
        if(comment.isEmpty()){
            _loadMessage.value = Event(LoadMessage.Error(ErrorMessage("评论不能为空",ApiError.unknownCode)))
            return
        }
        if(_publishCommentInfo.value == null){
            _loadMessage.value = Event(LoadMessage.Error(ErrorMessage("非法操作",ApiError.unknownCode)))
            return
        }

        _loadMessage.value = Event(LoadMessage.Loading)
        viewModelScope.launch {
            val result = publishCommentDataUseCase(
                PublishCommentDataUseCase.PublishCommentRequest(
                    _publishCommentInfo.value!!.momentId,_publishCommentInfo.value!!.type,
                    _publishCommentInfo.value?.toUserId,_publishCommentInfo.value?.commentId,
                    comment
                )
            )

            if(result is Resource.Success){
                _loadMessage.value = Event(LoadMessage.Success)
            } else {
                Logger.d("发布评论出错：$result")
                _loadMessage.value = Event(LoadMessage.Error(ErrorMessage(result.message,ApiError.unknownCode)))
            }
        }
    }
}